﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace IpQuery
{
    /// <summary>
    /// 使用爬去百度的查询数据
    /// </summary>
    public class Ip_BaiDu
    {
        public Ip_BaiDu()
        {

        }
        /// <summary>
        /// 远程加载ip地址的信息
        /// </summary>
        /// <param name="ip">ip地址</param>
        /// <returns></returns>
        public IpData_Baidu LoadData(string ip)
        {
            if (string.IsNullOrEmpty(ip))
                throw new Exception("传入的ip参数不能为空");
            if (RegexHelper.IsIpv4(ip) == false)
                throw new Exception("传入的ip不是ipv4格式");
            string url = getUrl(ip);
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "GET";
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            string result = "";
            using (StreamReader reader = new StreamReader(stream, Encoding.GetEncoding("gb2312")))
            {
                result = reader.ReadToEnd();
            }
            //解析结果
            IpData_Baidu model = Analyze(result);
            if (model == null)
                return null;
            model.Ipv4 = ip;
            model.NumberAddress = DomainHelper.IpToInt(ip);
            return model;
        }
        /// <summary>
        /// 批量获取ip的物理信息
        /// </summary>
        /// <param name="ipList">ip地址列表，逗号隔开</param>
        /// <returns></returns>
        public List<IpData_Baidu> LoadList(string ipList)
        {
            List<IpData_Baidu> list = new List<IpData_Baidu>();
            StringBuilder error = new StringBuilder();
            string[] temps = ipList.Split(',');
            if (temps != null)
            {
                foreach (var item in temps)
                {
                    try
                    {
                        IpData_Baidu model = LoadData(item);
                        if (model != null)
                            list.Add(model);
                    }
                    catch (Exception ex)
                    {
                        error.AppendLine(item + "解析失败，" + ex.Message);
                    }
                }
            }
            return list;
        }
        /// <summary>
        /// 解析返回结果
        /// </summary>
        /// <param name="result">返回结果</param>
        /// <returns></returns>
        private IpData_Baidu Analyze(string result)
        {
            if (string.IsNullOrEmpty(result))
                throw new Exception("请求远程数据为空");
            try
            {
                int start = result.IndexOf("{");
                int end = result.LastIndexOf("}");
                string temp = result.Substring(start, end - start + 1);
                JObject obj = JObject.Parse(temp);
                JArray dataArray = obj["data"] as JArray;
                if (dataArray == null)
                    return null;
                JObject dataObj = dataArray[0] as JObject;
                string location = dataObj["location"].ToString();

                IpData_Baidu model = new IpQuery.IpData_Baidu();
                model.Location = location;

                //百度返回数据的空格后边可能是运营商、可能是域名服务商
                //if (location.Contains(" "))
                //{
                //    string[] temps = location.Split(' ');
                //    model.Location = temps[0];
                //    model.TelecomOperators = temps[1];
                //}
                //else
                //{
                //    model.Location = location;
                //}

                return model;
            }
            catch (Exception ex)
            {
                throw new Exception("解析请求数据失败，" + ex.Message);
            }
        }
        /// <summary>
        /// 指定Ip获取请求的百度服务器地址
        /// </summary>
        /// <param name="ip">ip地址，目前已ipv4为多</param>
        /// <returns></returns>
        private string getUrl(string ip)
        {
            return string.Format(" https://sp0.baidu.com/8aQDcjqpAAV3otqbppnN2DJv/api.php?query={0}&co=&resource_id=6006&t=1478145571872&ie=utf8&oe=gbk&cb=op_aladdin_callback&format=json&tn=baidu&cb=jQuery110204481323950024978_1478145442947&_=1478145442951", ip);
        }
    }
}
